//
//  SegmenGoodsView.m
//  quxiangtao
//
//  Created by E人一铺 on 2018/11/15.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "SegmenGoodsView.h"
#import "BottomGoodsCollectionViewCell.h"
#import "PopupWebView.h"
#import <AudioToolbox/AudioToolbox.h>
#import "JDShoppingListModel.h"
#import "JDKeplerManager.h"
#import "ShopDetail/ShopDetailController.h"
static NSString *bottomGoodsCellID = @"bottomGoodsCellID";

@interface SegmenGoodsView () <UICollectionViewDelegate, UICollectionViewDataSource>
{
    SystemSoundID scoreClickBtnID;   // 自己设置的音效 (系统的振动音效 - kSystemSoundID_Vibrate)
    BOOL isYES;
}
@property (nonatomic, strong) PopupWebView *popopview;
@property (nonatomic, assign) NSInteger tempIndex;
@end

@implementation SegmenGoodsView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {

        [self setupUI];
        
        MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [footer setTitle:@"点击加载更多" forState:MJRefreshStateIdle];
        [footer setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
        [footer setTitle:@"没有更多数据！" forState:MJRefreshStateNoMoreData];
        footer.stateLabel.font = Font(17);
        
        // 设置颜色
        footer.stateLabel.textColor = Color999999;
        
        // 设置footer
        self.goodsCollectionView.mj_footer = footer;
        self.goodsCollectionView.mj_footer.hidden = NO;
        
        NSLog(@"%@", self.model.classid);
          AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"5a2e388b2886c.wav" ofType:@""]]), &scoreClickBtnID);
       
    }
    return self;
}

- (void)changeModel:(TbCategoryTitleModel *)model selectButtonIndex:(NSInteger)selectButtonIndex {
    [self.goodsArr removeAllObjects];
    [self.jdgoodsArr removeAllObjects];
    [UIView performWithoutAnimation:^{
        [self.goodsCollectionView reloadData];
    }];
    
    self.model = model;
    self.selectButtonIndex = selectButtonIndex;
    [self loadData];
}

- (void)loadData {
    
    self.page = 1;
    [self loadDataWithClassID:self.model.classid];
    [self.goodsCollectionView.mj_footer endRefreshing];
}

- (void)loadMoreData {
    
    self.page ++;
    
    [UIView performWithoutAnimation:^{
        [self.goodsCollectionView reloadData];
    }];
    
    [self loadDataWithClassID:self.model.classid];
    // 拿到当前的上拉刷新控件，结束刷新状态
    [self.goodsCollectionView.mj_footer endRefreshing];
    
}

- (void)loadDataWithClassID:(NSString *)classid {
    
    __weak typeof(self) weakSelf = self;
    if (self.selectButtonIndex == 4) {
        [JDShoppingListModel jdShoppingGoodListWitPage:self.page ClassID:classid successBlock:^(id responseObject) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSArray *arr = responseObject[@"data"];
                if (arr.count > 0 || weakSelf.jdgoodsArr.count > 0 ) {
                    if (weakSelf.page == 1) {
                        [weakSelf.jdgoodsArr removeAllObjects];
                        [weakSelf.jdgoodsArr addObjectsFromArray:arr];
                    }else {
                        [weakSelf.jdgoodsArr addObjectsFromArray:arr];
                    }
                    CGFloat height = 0;
                    int num = (int)weakSelf.jdgoodsArr.count / 2;
                    if (weakSelf.jdgoodsArr.count % 2 == 0) {
                        height = num * jisuan(525) + jisuan(170);
                    }else {
                        height = (num + 1) * jisuan(525) + jisuan(170);
                    }
                    
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (weakSelf.selectButtonIndex == 4) {
                        [UIView performWithoutAnimation:^{
                            [weakSelf.goodsCollectionView reloadData];
                        }];
                    }
                });
            });
            
        } failBlock:^(NSError *error) {
            
        }];

    }else {
        [TbGoodsListModel goodsListWithUrl:@"goods/index/goodsList" andPage:self.page withClassID:classid successBlock:^(id responseObject) {
            
            if ([responseObject[@"code"] integerValue] == 1) {
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    NSArray *arr = responseObject[@"data"];
                    if (arr.count > 0 || weakSelf.goodsArr.count > 0 ) {
                        if (weakSelf.page == 1) {
                            [weakSelf.goodsArr removeAllObjects];
                            [weakSelf.goodsArr addObjectsFromArray:arr];
                        }else {
                            [weakSelf.goodsArr addObjectsFromArray:arr];
                        }
                        CGFloat height = 0;
                        int num = (int)weakSelf.goodsArr.count / 2;
                        if (weakSelf.goodsArr.count % 2 == 0) {
                            height = num * jisuan(525) + jisuan(170);
                        }else {
                            height = (num + 1) * jisuan(525) + jisuan(170);
                        }
                        
                    }else {
                        
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (weakSelf.selectButtonIndex != 4) {
                            [UIView performWithoutAnimation:^{
                                [weakSelf.goodsCollectionView reloadData];
                            }];
                        }
                    });
                    
                });
              
            }else {
                
                [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
            }
            
        } failBlock:^(NSError *error) {
            
            if (error) {
//                [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
            }
            
        }];
    }
}


- (void)setupUI {
    
    [self addSubview:self.goodsCollectionView];
    
    WS(weakSelf)
    [self.goodsCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(weakSelf.mas_top).with.offset(10);
        make.left.mas_equalTo(weakSelf.mas_left).with.offset(jisuan(20));
        make.right.mas_equalTo(weakSelf.mas_right).with.offset(jisuan(-20));
        make.bottom.mas_equalTo(weakSelf.mas_bottom).with.offset(-Height_TabBar-Height_StatusBar);
        
    }];
    
}

#pragma mark -collectionView delegate、datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.selectButtonIndex == 4 ? self.jdgoodsArr.count : self.goodsArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    BottomGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:bottomGoodsCellID forIndexPath:indexPath];
    cell.backgroundColor = WhiteColor;
    cell.layer.cornerRadius = jisuan(10);
    cell.layer.masksToBounds = YES;
    if (self.selectButtonIndex == 4) {
        cell.jdModel = self.jdgoodsArr[indexPath.item];
    } else {
       cell.model = self.goodsArr[indexPath.item];
    }
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
//    static BOOL shouldPrevent;
//    if (shouldPrevent) return;
//    shouldPrevent = YES;
//    self.popopview = [[PopupWebView alloc] init];
//    self.popopview.hidden = YES;
//    self.popopview.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
//    [[UIApplication sharedApplication].keyWindow addSubview:self.popopview];

    WS(weakSelf);
    if ([CommonUserInfo sharedInstance].isLogin) {
        NSString *string = [NSString stringWithFormat:@"{\"user_id\" : \"%@\"}",[RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey]];
        [PPNetworkHelper POST:@"welfare/browse/index" parameters:@{@"json":string} success:^(id responseObject) {
            if ([responseObject[@"code"] intValue] == 1) {
                [weakSelf.popopview loadWithHtml:responseObject[@"data"][@"jiangli"]];
                weakSelf.popopview.hidden = NO;
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                AudioServicesPlaySystemSound(self->scoreClickBtnID);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    [weakSelf.popopview removeFromSuperview];
                    if (weakSelf.selectButtonIndex == 4) {
                        JDShoppingListModel *listModel = weakSelf.jdgoodsArr[indexPath.item];
                        [[JDKeplerManager sharedManager] jumpToTheProductDetailsPageSkuid:listModel.skuId Controller:weakSelf.parentVC];
                    } else {
                        ShopDetailController *vc = [[ShopDetailController alloc] init];
                        vc.model = self.goodsArr[indexPath.item];
                        [self.parentVC.navigationController pushViewController:vc animated:YES];
//                        TbGoodsListModel *model = weakSelf.goodsArr[indexPath.item];
//                        [[CommonAction sharedInstance] goToTbGoodsDetailWith:weakSelf.parentVC itemDetailPage:model.coupon_click_url];
                    }
//                    shouldPrevent = NO;
                });
            } else {
                if (weakSelf.selectButtonIndex == 4) {
                    JDShoppingListModel *listModel = weakSelf.jdgoodsArr[indexPath.item];
                    [[JDKeplerManager sharedManager] jumpToTheProductDetailsPageSkuid:listModel.skuId Controller:weakSelf.parentVC];
                } else {
                    ShopDetailController *vc = [[ShopDetailController alloc] init];
                    vc.model = self.goodsArr[indexPath.item];
                    [self.parentVC.navigationController pushViewController:vc animated:YES];
                }
//                shouldPrevent = NO;
            }
            
        } failure:^(NSError *error) {
//            shouldPrevent = NO;
            if (weakSelf.selectButtonIndex == 4) {
                JDShoppingListModel *listModel = weakSelf.jdgoodsArr[indexPath.item];
                [[JDKeplerManager sharedManager] jumpToTheProductDetailsPageSkuid:listModel.skuId Controller:weakSelf.parentVC];
            } else {
                ShopDetailController *vc = [[ShopDetailController alloc] init];
                vc.model = self.goodsArr[indexPath.item];
                [self.parentVC.navigationController pushViewController:vc animated:YES];
//                TbGoodsListModel *model = weakSelf.goodsArr[indexPath.item];
//                [[CommonAction sharedInstance] goToTbGoodsDetailWith:weakSelf.parentVC itemDetailPage:model.coupon_click_url];
            }
        }];
    } else {
//        shouldPrevent = NO;
        if (weakSelf.selectButtonIndex == 4) {
            JDShoppingListModel *listModel = weakSelf.jdgoodsArr[indexPath.item];
            [[JDKeplerManager sharedManager] jumpToTheProductDetailsPageSkuid:listModel.skuId Controller:weakSelf.parentVC];
        } else {
            if (![[CommonAction sharedInstance] isLoginWithParentVc:self.parentVC]) {
                return;
            }
            ShopDetailController *vc = [[ShopDetailController alloc] init];
            vc.model = self.goodsArr[indexPath.item];
            [self.parentVC.navigationController pushViewController:vc animated:YES];
//            TbGoodsListModel *model = weakSelf.goodsArr[indexPath.item];
//            [[CommonAction sharedInstance] goToTbGoodsDetailWith:weakSelf.parentVC itemDetailPage:model.coupon_click_url];
        }
        
    }
 
}



- (UICollectionView *)goodsCollectionView {
    
    if (!_goodsCollectionView) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(jisuan(350), jisuan(520));
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        flowLayout.minimumLineSpacing = jisuan(10);
        flowLayout.minimumInteritemSpacing = jisuan(10);
        _goodsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _goodsCollectionView.tag = 2018;
        _goodsCollectionView.backgroundColor = Colorf2f2f2;
        _goodsCollectionView.delegate = self;
        _goodsCollectionView.dataSource = self;
        _goodsCollectionView.scrollEnabled = YES;
        _goodsCollectionView.alwaysBounceVertical = YES;
        _goodsCollectionView.showsVerticalScrollIndicator = NO;
        _goodsCollectionView.showsHorizontalScrollIndicator = NO;
        [_goodsCollectionView registerClass:[BottomGoodsCollectionViewCell class] forCellWithReuseIdentifier:bottomGoodsCellID];
        
        if (@available (iOS 11.0, *)) {
            
            _goodsCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
    }
    
    return _goodsCollectionView;
    
}

- (NSMutableArray *)goodsArr {
    if (!_goodsArr) {
        _goodsArr = [NSMutableArray array];
    }
    return _goodsArr;
}

- (NSMutableArray *)jdgoodsArr {
    if (!_jdgoodsArr) {
        _jdgoodsArr = [[NSMutableArray alloc] init];
    }
    return _jdgoodsArr;
}



@end
